#include "menuitem.h"

MenuItem::MenuItem(const QString &text, const QPixmap & pixmap, QGraphicsItem *parent) : QGraphicsWidget(parent), m_text(text), m_pixmap(pixmap)
{
    m_hovered = false;
    setAcceptsHoverEvents(true);
    setCacheMode(DeviceCoordinateCache);
    setMinimumSize(boundingRect().size()); // TODO: resize
    setMaximumSize(boundingRect().size()); // TODO: resize
}

QRectF MenuItem::boundingRect() const
{
    return QRectF(0, 0, 400, 80);
}

void MenuItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    bool down = option->state & QStyle::State_Sunken;

    painter->save();
    painter->setRenderHint(QPainter::Antialiasing, true);
    // draw button
    QBrush brush(painter->brush());
    QColor cColor;

    if (m_hovered)
    {
        cColor = QColor(225,155,255, 50);
    }
    else
    {
        cColor = QColor(125,255,210, 50);
    }

    brush.setColor(cColor);

    brush.setStyle(Qt::SolidPattern);
    QPen pen(painter->pen());

    pen.setColor(cColor);

    painter->setBrush(brush);
    painter->setPen(pen);
    painter->drawRoundedRect(boundingRect(), 15, 15, Qt::AbsoluteSize);

    if (down)
        painter->translate(2, 2);

    painter->drawRoundedRect(boundingRect().adjusted(4,4,-4,-4), 15, 15, Qt::AbsoluteSize);

    //draw icon if present
    painter->drawPixmap(24, 8, 64, 64, m_pixmap);

    // draw text
    QFont font(painter->font());
    font.setBold(true);
    font.setPointSize(16);
    pen.setColor(QColor(0,0,0));
    painter->setFont(font);
    painter->setPen(pen);

    QFontMetrics fm(font);
    int iTextWidth = fm.width(m_text);
    painter->drawText(250 - iTextWidth / 2, 50, m_text);

    painter->restore();
}

void MenuItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        emit pressed();
        update();
        event->accept();
    }
    else if (event->button() == Qt::RightButton)
    {
        emit rightClicked();
        event->accept();
    }
}

void MenuItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    update();
}

void MenuItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
    m_hovered  = true;
    update();
}

void MenuItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
    m_hovered = false;
    update();
}
